import React, { useState, useCallback, useEffect } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import {
  Card,
  Form,
  Input,
  Select,
  Button,
  Space,
  Table,
  Tag,
  Modal,
  message,
  Row,
  Col,
  Radio,
  InputNumber,
  Divider,
  Typography,
  Tooltip,
  Progress,
  Spin,
  Empty,
  Alert,
  List,
} from "antd";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  CopyOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  FileTextOutlined,
  ExportOutlined,
  RobotOutlined,
  EyeOutlined,
  DownloadOutlined,
  BulbOutlined,
  SearchOutlined,
} from "@ant-design/icons";
import styled from "styled-components";
import TemplateForm from "./components/TemplateForm";
import ExamPreview from "./components/ExamPreview";
import type { QuestionType, DifficultyLevel, ExamTemplate } from "./types";
import {
  examApi as examAPI,
  questionAPI,
  templateAPI,
  Question as ServiceQuestion,
} from "../../../services/examService";
import AIGenerationModal from "./components/AIGenerationModal";
import SmartComposer from "./components/SmartComposer";
import { examStore } from "../../../utils/examStore";

const { TextArea } = Input;
const { Option } = Select;
const { Title, Text } = Typography;
const { confirm } = Modal;

// 统一Question类型，基于本地类型定义
interface Question {
  id: string;
  type: QuestionType;
  difficulty: DifficultyLevel;
  score: number;
  content: string;
  answer: string;
  knowledge: string[];
  options?: string[];
  analysis?: string;
  tags?: string[];
  createTime: string;
  updateTime: string;
}

interface FormValues
  extends Omit<Question, "id" | "createTime" | "updateTime"> {}

const StyledCard = styled(Card)`
  margin-bottom: 24px;
  .ant-card-head-title {
    font-weight: bold;
  }
`;

const DifficultyTag = styled(Tag)<{ $difficulty: DifficultyLevel }>`
  &.ant-tag-green {
    background-color: #f6ffed;
  }
  &.ant-tag-orange {
    background-color: #fff7e6;
  }
  &.ant-tag-red {
    background-color: #fff1f0;
  }
`;

const TypeTag = styled(Tag)<{ $type: QuestionType }>`
  &.ant-tag-blue {
    background-color: #e6f7ff;
  }
  &.ant-tag-purple {
    background-color: #f9f0ff;
  }
  &.ant-tag-cyan {
    background-color: #e6fffb;
  }
`;

const ExamGeneration: React.FC = () => {
  const location = useLocation();
  const navigate = useNavigate();
  
  // 状态管理
  const [questions, setQuestions] = useState<Question[]>([]);
  const [templates, setTemplates] = useState<ExamTemplate[]>([]);
  const [loading, setLoading] = useState(true);
  const [questionsLoading, setQuestionsLoading] = useState(false);

  const [selectedQuestion, setSelectedQuestion] = useState<string | null>(null);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isTemplateModalVisible, setIsTemplateModalVisible] = useState(false);
  const [isGenerating, setIsGenerating] = useState(false);
  const [form] = Form.useForm<FormValues>();
  const [searchForm] = Form.useForm();
  const [templateForm] = Form.useForm();
  const [selectedTemplate, setSelectedTemplate] = useState<string | null>(null);
  const [isPreviewVisible, setIsPreviewVisible] = useState(false);
  const [examData, setExamData] = useState<{
    templateName: string;
    totalScore: number;
    duration: number;
    questions: Question[];
  } | null>(null);

  // 分页状态
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 新增智能组卷相关状态
  const [smartComposerVisible, setSmartComposerVisible] = useState(false);

  // AI生成相关状态
  const [aiModalVisible, setAiModalVisible] = useState(false);
  
  // AI生成进度状态
  const [generationProgress, setGenerationProgress] = useState(0);
  const [generationStatus, setGenerationStatus] = useState("");

  // 批量操作状态
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [selectedQuestions, setSelectedQuestions] = useState<Question[]>([]);
  
  // 题目类型选择状态
  const [questionType, setQuestionType] = useState<"exam" | "homework">("exam");
  const [selectedCourse, setSelectedCourse] = useState<{id: string, name: string} | null>(null);

  // 初始化数据
  useEffect(() => {
    loadInitialData();
    
    // 处理路由参数
    if (location.state) {
      const { courseId, courseName, type } = location.state as any;
      if (courseId && courseName) {
        setSelectedCourse({ id: courseId, name: courseName });
      }
      if (type) {
        setQuestionType(type);
      }
    }
  }, [location.state]);

  const loadInitialData = async () => {
    setLoading(true);
    try {
      await Promise.all([loadQuestions(), loadTemplates()]);
    } catch (error) {
      console.error("初始化数据失败:", error);
      message.error("数据加载失败，请刷新页面重试");
    } finally {
      setLoading(false);
    }
  };

  // 检查是否使用本地模式
  const isLocalMode = () => {
    // 使用本地模式
    return true;
  };

  // 加载题目列表
  const loadQuestions = async (params?: any) => {
    setQuestionsLoading(true);
    try {
      // 检查是否使用本地模式
      if (isLocalMode()) {
        // 使用模拟数据 - 扩展题库到30道题目
        const mockQuestions: Question[] = [
          {
            id: "1",
            type: "choice",
            difficulty: "easy",
            score: 5,
            content: "以下哪个不是JavaScript的基本数据类型？",
            answer: "D",
            knowledge: ["JavaScript基础", "数据类型"],
            options: ["String", "Number", "Boolean", "Array"],
            analysis: "JavaScript的基本数据类型包括String、Number、Boolean、Undefined、Null、Symbol，Array是引用类型。",
            tags: ["基础", "重点"],
            createTime: "2024-01-15",
            updateTime: "2024-01-15",
          },
          {
            id: "2",
            type: "programming",
            difficulty: "medium",
            score: 20,
            content: "请编写一个函数，实现数组去重功能。",
            answer: "function unique(arr) { return [...new Set(arr)]; }",
            knowledge: ["JavaScript", "数组操作", "Set数据结构"],
            analysis: "使用ES6的Set数据结构可以快速实现数组去重，Set会自动去除重复元素。",
            tags: ["编程", "实用"],
            createTime: "2024-01-16",
            updateTime: "2024-01-16",
          },
          {
            id: "3",
            type: "analysis",
            difficulty: "hard",
            score: 15,
            content: "分析React中useState和useEffect的区别和使用场景。",
            answer: "useState用于状态管理，useEffect用于副作用处理。useState在组件重新渲染时保持状态，useEffect在组件挂载、更新或卸载时执行。",
            knowledge: ["React", "Hooks", "状态管理"],
            analysis: "useState是React Hooks中用于状态管理的Hook，useEffect是用于处理副作用的Hook，两者在React函数组件中经常配合使用。",
            tags: ["React", "难点"],
            createTime: "2024-01-17",
            updateTime: "2024-01-17",
          },
          {
            id: "4",
            type: "choice",
            difficulty: "medium",
            score: 5,
            content: "在CSS中，以下哪个属性可以改变元素的显示类型？",
            answer: "A",
            knowledge: ["CSS", "布局"],
            options: ["display", "position", "float", "clear"],
            analysis: "display属性用于设置元素的显示类型，如block、inline、flex等。",
            tags: ["CSS", "布局"],
            createTime: "2024-01-18",
            updateTime: "2024-01-18",
          },
          {
            id: "5",
            type: "programming",
            difficulty: "easy",
            score: 10,
            content: "编写一个函数，计算两个数字的和。",
            answer: "function add(a, b) { return a + b; }",
            knowledge: ["JavaScript", "函数", "基础语法"],
            analysis: "这是一个基础的函数编写题目，考察函数定义和返回值的使用。",
            tags: ["基础", "函数"],
            createTime: "2024-01-19",
            updateTime: "2024-01-19",
          },
          {
            id: "6",
            type: "choice",
            difficulty: "medium",
            score: 5,
            content: "React中的虚拟DOM是什么？",
            answer: "A",
            knowledge: ["React", "虚拟DOM", "性能优化"],
            options: ["内存中的JavaScript对象", "真实的DOM元素", "CSS样式对象", "HTML字符串"],
            analysis: "虚拟DOM是React中的一个概念，它是真实DOM在内存中的JavaScript对象表示。",
            tags: ["React", "核心概念"],
            createTime: "2024-01-20",
            updateTime: "2024-01-20",
          },
          {
            id: "7",
            type: "programming",
            difficulty: "medium",
            score: 15,
            content: "实现一个简单的Promise类，支持then方法。",
            answer: "class MyPromise {\n  constructor(executor) {\n    this.state = 'pending';\n    this.value = null;\n    this.onFulfilledCallbacks = [];\n    this.onRejectedCallbacks = [];\n    \n    const resolve = (value) => {\n      if (this.state === 'pending') {\n        this.state = 'fulfilled';\n        this.value = value;\n        this.onFulfilledCallbacks.forEach(cb => cb(value));\n      }\n    };\n    \n    const reject = (reason) => {\n      if (this.state === 'pending') {\n        this.state = 'rejected';\n        this.value = reason;\n        this.onRejectedCallbacks.forEach(cb => cb(reason));\n      }\n    };\n    \n    executor(resolve, reject);\n  }\n  \n  then(onFulfilled, onRejected) {\n    if (this.state === 'fulfilled') {\n      onFulfilled(this.value);\n    } else if (this.state === 'rejected') {\n      onRejected(this.value);\n    } else {\n      this.onFulfilledCallbacks.push(onFulfilled);\n      this.onRejectedCallbacks.push(onRejected);\n    }\n  }\n}",
            knowledge: ["JavaScript", "Promise", "异步编程"],
            analysis: "这是一个Promise的简化实现，展示了Promise的基本原理和状态管理。",
            tags: ["JavaScript", "异步", "难点"],
            createTime: "2024-01-21",
            updateTime: "2024-01-21",
          },
          {
            id: "8",
            type: "analysis",
            difficulty: "hard",
            score: 20,
            content: "分析JavaScript中的闭包概念，并说明其优缺点。",
            answer: "闭包是指函数和其词法环境的组合，函数可以访问其外部作用域中的变量。优点：数据私有化、模块化开发、函数工厂。缺点：内存泄漏风险、性能影响。",
            knowledge: ["JavaScript", "闭包", "作用域"],
            analysis: "闭包是JavaScript中的重要概念，理解闭包对于深入理解JavaScript语言特性非常重要。",
            tags: ["JavaScript", "核心概念", "难点"],
            createTime: "2024-01-22",
            updateTime: "2024-01-22",
          },
          {
            id: "9",
            type: "choice",
            difficulty: "easy",
            score: 5,
            content: "以下哪个是ES6的新特性？",
            answer: "C",
            knowledge: ["JavaScript", "ES6", "新特性"],
            options: ["var关键字", "function关键字", "箭头函数", "for循环"],
            analysis: "箭头函数是ES6引入的新特性，提供了更简洁的函数语法。",
            tags: ["JavaScript", "ES6"],
            createTime: "2024-01-23",
            updateTime: "2024-01-23",
          },
          {
            id: "10",
            type: "programming",
            difficulty: "hard",
            score: 25,
            content: "实现一个LRU缓存算法。",
            answer: "class LRUCache {\n  constructor(capacity) {\n    this.capacity = capacity;\n    this.cache = new Map();\n  }\n  \n  get(key) {\n    if (this.cache.has(key)) {\n      const value = this.cache.get(key);\n      this.cache.delete(key);\n      this.cache.set(key, value);\n      return value;\n    }\n    return -1;\n  }\n  \n  put(key, value) {\n    if (this.cache.has(key)) {\n      this.cache.delete(key);\n    } else if (this.cache.size >= this.capacity) {\n      const firstKey = this.cache.keys().next().value;\n      this.cache.delete(firstKey);\n    }\n    this.cache.set(key, value);\n  }\n}",
            knowledge: ["算法", "数据结构", "缓存"],
            analysis: "LRU（Least Recently Used）缓存是一种常用的缓存淘汰策略。",
            tags: ["算法", "数据结构", "难点"],
            createTime: "2024-01-24",
            updateTime: "2024-01-24",
          },
          {
            id: "11",
            type: "choice",
            difficulty: "medium",
            score: 5,
            content: "React中的Context主要用于解决什么问题？",
            answer: "B",
            knowledge: ["React", "Context", "状态管理"],
            options: ["组件通信", "跨层级数据传递", "样式管理", "路由管理"],
            analysis: "React Context主要用于解决跨层级组件间的数据传递问题，避免props drilling。",
            tags: ["React", "状态管理"],
            createTime: "2024-01-25",
            updateTime: "2024-01-25",
          },
          {
            id: "12",
            type: "programming",
            difficulty: "medium",
            score: 15,
            content: "编写一个函数，实现深拷贝功能。",
            answer: "function deepClone(obj) {\n  if (obj === null || typeof obj !== 'object') return obj;\n  if (obj instanceof Date) return new Date(obj.getTime());\n  if (obj instanceof Array) return obj.map(item => deepClone(item));\n  if (typeof obj === 'object') {\n    const clonedObj = {};\n    for (let key in obj) {\n      if (obj.hasOwnProperty(key)) {\n        clonedObj[key] = deepClone(obj[key]);\n      }\n    }\n    return clonedObj;\n  }\n}",
            knowledge: ["JavaScript", "对象操作", "深拷贝"],
            analysis: "深拷贝需要考虑各种数据类型，包括基本类型、数组、对象、Date等。",
            tags: ["JavaScript", "对象操作"],
            createTime: "2024-01-26",
            updateTime: "2024-01-26",
          },
          {
            id: "13",
            type: "analysis",
            difficulty: "medium",
            score: 15,
            content: "解释JavaScript中的事件循环机制。",
            answer: "事件循环是JavaScript处理异步操作的机制，包括调用栈、任务队列、微任务队列等。执行顺序：同步代码 -> 微任务 -> 宏任务。",
            knowledge: ["JavaScript", "事件循环", "异步编程"],
            analysis: "理解事件循环对于编写正确的异步代码非常重要。",
            tags: ["JavaScript", "异步", "核心概念"],
            createTime: "2024-01-27",
            updateTime: "2024-01-27",
          },
          {
            id: "14",
            type: "choice",
            difficulty: "easy",
            score: 5,
            content: "CSS中的flexbox布局中，justify-content属性的默认值是什么？",
            answer: "A",
            knowledge: ["CSS", "Flexbox", "布局"],
            options: ["flex-start", "center", "flex-end", "space-between"],
            analysis: "justify-content的默认值是flex-start，表示项目从主轴起点开始排列。",
            tags: ["CSS", "布局"],
            createTime: "2024-01-28",
            updateTime: "2024-01-28",
          },
          {
            id: "15",
            type: "programming",
            difficulty: "hard",
            score: 20,
            content: "实现一个简单的Vue响应式系统。",
            answer: "class Dep {\n  constructor() {\n    this.subscribers = [];\n  }\n  \n  depend() {\n    if (activeEffect) {\n      this.subscribers.push(activeEffect);\n    }\n  }\n  \n  notify() {\n    this.subscribers.forEach(effect => effect());\n  }\n}\n\nfunction reactive(obj) {\n  Object.keys(obj).forEach(key => {\n    const dep = new Dep();\n    let value = obj[key];\n    Object.defineProperty(obj, key, {\n      get() {\n        dep.depend();\n        return value;\n      },\n      set(newValue) {\n        value = newValue;\n        dep.notify();\n      }\n    });\n  });\n  return obj;\n}",
            knowledge: ["Vue", "响应式", "数据绑定"],
            analysis: "这是一个简化的Vue响应式系统实现，展示了依赖收集和派发更新的基本原理。",
            tags: ["Vue", "响应式", "难点"],
            createTime: "2024-01-29",
            updateTime: "2024-01-29",
          },
          {
            id: "16",
            type: "choice",
            difficulty: "medium",
            score: 5,
            content: "TypeScript中的泛型主要用于什么？",
            answer: "A",
            knowledge: ["TypeScript", "泛型", "类型系统"],
            options: ["代码复用和类型安全", "提高运行性能", "减少代码体积", "简化语法"],
            analysis: "TypeScript的泛型允许在定义函数、接口或类时不预先指定具体的类型，而是在使用时再指定，提高代码复用性和类型安全性。",
            tags: ["TypeScript", "泛型"],
            createTime: "2024-01-30",
            updateTime: "2024-01-30",
          },
          {
            id: "17",
            type: "programming",
            difficulty: "medium",
            score: 15,
            content: "实现一个防抖函数。",
            answer: "function debounce(func, wait) {\n  let timeout;\n  return function executedFunction(...args) {\n    const later = () => {\n      clearTimeout(timeout);\n      func(...args);\n    };\n    clearTimeout(timeout);\n    timeout = setTimeout(later, wait);\n  };\n}",
            knowledge: ["JavaScript", "函数", "性能优化"],
            analysis: "防抖函数可以限制函数的执行频率，避免频繁调用导致的性能问题。",
            tags: ["JavaScript", "性能优化"],
            createTime: "2024-01-31",
            updateTime: "2024-01-31",
          },
          {
            id: "18",
            type: "analysis",
            difficulty: "hard",
            score: 15,
            content: "分析前端性能优化的主要策略。",
            answer: "前端性能优化策略包括：1. 减少HTTP请求（合并文件、使用CDN）；2. 优化资源加载（懒加载、预加载）；3. 代码优化（压缩、Tree Shaking）；4. 缓存策略（浏览器缓存、Service Worker）；5. 渲染优化（虚拟滚动、防抖节流）。",
            knowledge: ["前端", "性能优化", "最佳实践"],
            analysis: "性能优化是前端开发中的重要课题，需要从多个维度进行考虑。",
            tags: ["前端", "性能优化", "综合"],
            createTime: "2024-02-01",
            updateTime: "2024-02-01",
          },
          {
            id: "19",
            type: "choice",
            difficulty: "easy",
            score: 5,
            content: "Node.js中的事件驱动模型基于什么？",
            answer: "B",
            knowledge: ["Node.js", "事件驱动", "异步编程"],
            options: ["多线程模型", "事件循环", "进程模型", "协程模型"],
            analysis: "Node.js采用事件驱动、非阻塞I/O模型，基于事件循环机制实现异步处理。",
            tags: ["Node.js", "事件驱动"],
            createTime: "2024-02-02",
            updateTime: "2024-02-02",
          },
          {
            id: "20",
            type: "programming",
            difficulty: "medium",
            score: 15,
            content: "实现一个节流函数。",
            answer: "function throttle(func, limit) {\n  let inThrottle;\n  return function() {\n    const args = arguments;\n    const context = this;\n    if (!inThrottle) {\n      func.apply(context, args);\n      inThrottle = true;\n      setTimeout(() => inThrottle = false, limit);\n    }\n  }\n}",
            knowledge: ["JavaScript", "函数", "性能优化"],
            analysis: "节流函数确保函数在指定时间内最多执行一次，常用于滚动事件等场景。",
            tags: ["JavaScript", "性能优化"],
            createTime: "2024-02-03",
            updateTime: "2024-02-03",
          },
          {
            id: "21",
            type: "choice",
            difficulty: "medium",
            score: 5,
            content: "Webpack的主要作用是什么？",
            answer: "A",
            knowledge: ["Webpack", "模块打包", "构建工具"],
            options: ["模块打包和资源管理", "代码压缩", "语法转换", "服务器部署"],
            analysis: "Webpack是一个现代JavaScript应用程序的静态模块打包器，主要用于模块打包和资源管理。",
            tags: ["Webpack", "构建工具"],
            createTime: "2024-02-04",
            updateTime: "2024-02-04",
          },
          {
            id: "22",
            type: "programming",
            difficulty: "hard",
            score: 20,
            content: "实现一个简单的发布订阅模式。",
            answer: "class EventEmitter {\n  constructor() {\n    this.events = {};\n  }\n  \n  on(event, callback) {\n    if (!this.events[event]) {\n      this.events[event] = [];\n    }\n    this.events[event].push(callback);\n  }\n  \n  emit(event, ...args) {\n    if (this.events[event]) {\n      this.events[event].forEach(callback => callback(...args));\n    }\n  }\n  \n  off(event, callback) {\n    if (this.events[event]) {\n      this.events[event] = this.events[event].filter(cb => cb !== callback);\n    }\n  }\n}",
            knowledge: ["JavaScript", "设计模式", "事件系统"],
            analysis: "发布订阅模式是一种常用的设计模式，用于解耦事件发布者和订阅者。",
            tags: ["JavaScript", "设计模式", "难点"],
            createTime: "2024-02-05",
            updateTime: "2024-02-05",
          },
          {
            id: "23",
            type: "analysis",
            difficulty: "medium",
            score: 15,
            content: "解释RESTful API的设计原则。",
            answer: "RESTful API设计原则包括：1. 使用HTTP动词表示操作（GET、POST、PUT、DELETE）；2. 使用名词表示资源；3. 使用HTTP状态码表示结果；4. 无状态设计；5. 统一接口；6. 分层系统。",
            knowledge: ["API设计", "REST", "Web服务"],
            analysis: "RESTful API是现代Web服务的主流设计风格，遵循这些原则可以提高API的可维护性和可扩展性。",
            tags: ["API设计", "REST", "综合"],
            createTime: "2024-02-06",
            updateTime: "2024-02-06",
          },
          {
            id: "24",
            type: "choice",
            difficulty: "easy",
            score: 5,
            content: "Git中的HEAD指针指向什么？",
            answer: "A",
            knowledge: ["Git", "版本控制", "分支管理"],
            options: ["当前分支的最新提交", "远程仓库", "工作目录", "暂存区"],
            analysis: "HEAD指针指向当前分支的最新提交，表示当前工作目录的状态。",
            tags: ["Git", "版本控制"],
            createTime: "2024-02-07",
            updateTime: "2024-02-07",
          },
          {
            id: "25",
            type: "programming",
            difficulty: "medium",
            score: 15,
            content: "实现一个简单的观察者模式。",
            answer: "class Subject {\n  constructor() {\n    this.observers = [];\n  }\n  \n  addObserver(observer) {\n    this.observers.push(observer);\n  }\n  \n  removeObserver(observer) {\n    this.observers = this.observers.filter(obs => obs !== observer);\n  }\n  \n  notify(data) {\n    this.observers.forEach(observer => observer.update(data));\n  }\n}\n\nclass Observer {\n  update(data) {\n    console.log('Observer received:', data);\n  }\n}",
            knowledge: ["JavaScript", "设计模式", "观察者模式"],
            analysis: "观察者模式定义了一种一对多的依赖关系，当一个对象状态改变时，所有依赖者都会得到通知。",
            tags: ["JavaScript", "设计模式"],
            createTime: "2024-02-08",
            updateTime: "2024-02-08",
          },
          {
            id: "26",
            type: "choice",
            difficulty: "medium",
            score: 5,
            content: "Docker容器与虚拟机的区别是什么？",
            answer: "B",
            knowledge: ["Docker", "容器化", "虚拟化"],
            options: ["容器更安全", "容器共享主机内核", "虚拟机更轻量", "容器需要更多资源"],
            analysis: "Docker容器与虚拟机的主要区别是容器共享主机内核，而虚拟机有独立的操作系统内核。",
            tags: ["Docker", "容器化"],
            createTime: "2024-02-09",
            updateTime: "2024-02-09",
          },
          {
            id: "27",
            type: "programming",
            difficulty: "hard",
            score: 20,
            content: "实现一个简单的状态机。",
            answer: "class StateMachine {\n  constructor(initialState) {\n    this.state = initialState;\n    this.transitions = {};\n  }\n  \n  addTransition(from, to, condition) {\n    if (!this.transitions[from]) {\n      this.transitions[from] = [];\n    }\n    this.transitions[from].push({ to, condition });\n  }\n  \n  transition(input) {\n    const currentTransitions = this.transitions[this.state];\n    if (currentTransitions) {\n      for (let transition of currentTransitions) {\n        if (transition.condition(input)) {\n          this.state = transition.to;\n          return true;\n        }\n      }\n    }\n    return false;\n  }\n  \n  getState() {\n    return this.state;\n  }\n}",
            knowledge: ["JavaScript", "状态机", "设计模式"],
            analysis: "状态机是一种计算模型，用于描述对象在不同状态下的行为。",
            tags: ["JavaScript", "状态机", "难点"],
            createTime: "2024-02-10",
            updateTime: "2024-02-10",
          },
          {
            id: "28",
            type: "analysis",
            difficulty: "medium",
            score: 15,
            content: "分析微前端架构的优势和挑战。",
            answer: "微前端优势：1. 技术栈独立；2. 团队自治；3. 独立部署；4. 渐进式升级。挑战：1. 应用间通信复杂；2. 性能开销；3. 用户体验一致性；4. 构建和部署复杂度增加。",
            knowledge: ["微前端", "架构设计", "前端工程化"],
            analysis: "微前端是一种新兴的前端架构模式，适合大型应用的开发和维护。",
            tags: ["微前端", "架构设计", "综合"],
            createTime: "2024-02-11",
            updateTime: "2024-02-11",
          },
          {
            id: "29",
            type: "choice",
            difficulty: "easy",
            score: 5,
            content: "HTTP/2的主要改进是什么？",
            answer: "C",
            knowledge: ["HTTP", "网络协议", "性能优化"],
            options: ["更安全的加密", "更简单的语法", "多路复用", "更小的数据包"],
            analysis: "HTTP/2的主要改进包括多路复用、服务器推送、头部压缩等，其中多路复用是最重要的特性。",
            tags: ["HTTP", "网络协议"],
            createTime: "2024-02-12",
            updateTime: "2024-02-12",
          },
          {
            id: "30",
            type: "programming",
            difficulty: "medium",
            score: 15,
            content: "实现一个简单的中间件系统。",
            answer: "class Middleware {\n  constructor() {\n    this.middlewares = [];\n  }\n  \n  use(fn) {\n    this.middlewares.push(fn);\n  }\n  \n  execute(context) {\n    let index = 0;\n    const next = () => {\n      if (index < this.middlewares.length) {\n        const middleware = this.middlewares[index++];\n        middleware(context, next);\n      }\n    };\n    next();\n  }\n}",
            knowledge: ["JavaScript", "中间件", "设计模式"],
            analysis: "中间件模式允许在请求处理过程中插入多个处理函数，常用于Web框架中。",
            tags: ["JavaScript", "中间件", "设计模式"],
            createTime: "2024-02-13",
            updateTime: "2024-02-13",
          },
        ];
        
        setQuestions(mockQuestions);
        setPagination((prev) => ({
          ...prev,
          total: mockQuestions.length,
        }));
        return;
      }

      // 真实API调用
      const response = await questionAPI.getQuestions({
        page: pagination.current,
        size: pagination.pageSize,
        ...params,
      });

      if (response.data) {
        setQuestions(response.data.records || response.data.list || []);
        setPagination((prev) => ({
          ...prev,
          total: response.data.total || 0,
        }));
      }
    } catch (error) {
      console.error("加载题目失败:", error);
      message.error("题目加载失败，请稍后重试");
      
      // 使用模拟数据
      const mockQuestions: Question[] = [
        {
          id: "1",
          type: "choice",
          difficulty: "easy",
          score: 5,
          content: "以下哪个不是JavaScript的基本数据类型？",
          answer: "D",
          knowledge: ["JavaScript基础", "数据类型"],
          options: ["String", "Number", "Boolean", "Array"],
          analysis: "JavaScript的基本数据类型包括String、Number、Boolean、Undefined、Null、Symbol，Array是引用类型。",
          tags: ["基础", "重点"],
          createTime: "2024-01-15",
          updateTime: "2024-01-15",
        },
        {
          id: "2",
          type: "programming",
          difficulty: "medium",
          score: 20,
          content: "请编写一个函数，实现数组去重功能。",
          answer: "function unique(arr) { return [...new Set(arr)]; }",
          knowledge: ["JavaScript", "数组操作", "Set数据结构"],
          analysis: "使用ES6的Set数据结构可以快速实现数组去重，Set会自动去除重复元素。",
          tags: ["编程", "实用"],
          createTime: "2024-01-16",
          updateTime: "2024-01-16",
        },
        {
          id: "3",
          type: "analysis",
          difficulty: "hard",
          score: 15,
          content: "分析React中useState和useEffect的区别和使用场景。",
          answer: "useState用于状态管理，useEffect用于副作用处理。useState在组件重新渲染时保持状态，useEffect在组件挂载、更新或卸载时执行。",
          knowledge: ["React", "Hooks", "状态管理"],
          analysis: "useState是React Hooks中用于状态管理的Hook，useEffect是用于处理副作用的Hook，两者在React函数组件中经常配合使用。",
          tags: ["React", "难点"],
          createTime: "2024-01-17",
          updateTime: "2024-01-17",
        },
        {
          id: "4",
          type: "choice",
          difficulty: "medium",
          score: 5,
          content: "在CSS中，以下哪个属性可以改变元素的显示类型？",
          answer: "A",
          knowledge: ["CSS", "布局"],
          options: ["display", "position", "float", "clear"],
          analysis: "display属性用于设置元素的显示类型，如block、inline、flex等。",
          tags: ["CSS", "布局"],
          createTime: "2024-01-18",
          updateTime: "2024-01-18",
        },
        {
          id: "5",
          type: "programming",
          difficulty: "easy",
          score: 10,
          content: "编写一个函数，计算两个数字的和。",
          answer: "function add(a, b) { return a + b; }",
          knowledge: ["JavaScript", "函数", "基础语法"],
          analysis: "这是一个基础的函数编写题目，考察函数定义和返回值的使用。",
          tags: ["基础", "函数"],
          createTime: "2024-01-19",
          updateTime: "2024-01-19",
        },
      ];
      
      setQuestions(mockQuestions);
      setPagination((prev) => ({
        ...prev,
        total: mockQuestions.length,
      }));
    } finally {
      setQuestionsLoading(false);
    }
  };

  // 加载模板列表 - 使用统一的examStore数据
  const loadTemplates = async () => {
    try {
      // 直接使用examStore中的模板数据，确保数据一致性
      const storeTemplates = examStore.getTemplates();
      
      // 转换为当前界面需要的格式
      const convertedTemplates: ExamTemplate[] = storeTemplates.map(template => ({
        id: template.id,
        name: template.name,
        totalScore: template.totalScore,
        duration: template.duration,
        questionDistribution: {
          choice: { 
            count: template.questionTypes.choice, 
            score: template.questionTypes.choice * 4, 
            difficulty: [template.difficulty === "简单" ? "easy" : template.difficulty === "中等" ? "medium" : "hard"] 
          },
          programming: { 
            count: template.questionTypes.programming, 
            score: template.questionTypes.programming * 15, 
            difficulty: [template.difficulty === "简单" ? "easy" : template.difficulty === "中等" ? "medium" : "hard"] 
          },
          analysis: { 
            count: template.questionTypes.analysis, 
            score: template.questionTypes.analysis * 10, 
            difficulty: [template.difficulty === "简单" ? "easy" : template.difficulty === "中等" ? "medium" : "hard"] 
          },
          fill: { 
            count: template.questionTypes.fill, 
            score: template.questionTypes.fill * 3, 
            difficulty: [template.difficulty === "简单" ? "easy" : template.difficulty === "中等" ? "medium" : "hard"] 
          },
          essay: { 
            count: template.questionTypes.essay, 
            score: template.questionTypes.essay * 8, 
            difficulty: [template.difficulty === "简单" ? "easy" : template.difficulty === "中等" ? "medium" : "hard"] 
          },
        },
        description: template.description,
        difficulty: template.difficulty,
        subject: template.subject,
        tags: template.tags,
        createTime: template.createTime,
        updateTime: template.updateTime,
        usageCount: template.usageCount,
        isDefault: template.isDefault,
        creator: template.creator,
      }));
      
      setTemplates(convertedTemplates);
    } catch (error) {
      console.error("加载模板失败:", error);
      message.error("模板加载失败，请稍后重试");
      setTemplates([]);
    }
  };

  // 搜索处理函数
  const handleSearch = async (values: any) => {
    await loadQuestions(values);
  };

  const showModal = () => {
    setIsModalVisible(true);
  };

  const handleOk = async () => {
    try {
      const values = await form.validateFields();

      if (selectedQuestion) {
        // 更新题目
        try {
          await questionAPI.updateQuestion(Number(selectedQuestion), values);
          message.success("题目更新成功！");
        } catch (error) {
          console.error("API更新失败，使用本地更新:", error);
          // 本地更新
          setQuestions(prev => prev.map(q => 
            q.id === selectedQuestion ? { ...q, ...values } : q
          ));
          message.success("题目更新成功！");
        }
      } else {
        // 添加新题目
        try {
          await questionAPI.createQuestion(values);
          message.success("题目添加成功！");
        } catch (error) {
          console.error("API创建失败，使用本地创建:", error);
          // 本地创建
          const newQuestion: Question = {
            id: Date.now().toString(),
            ...values,
            createTime: new Date().toISOString().split('T')[0],
            updateTime: new Date().toISOString().split('T')[0],
          };
          setQuestions(prev => [newQuestion, ...prev]);
          message.success("题目添加成功！");
        }
      }

      setIsModalVisible(false);
      form.resetFields();
      setSelectedQuestion(null);
      loadQuestions(); // 重新加载题目列表
    } catch (error) {
      console.error("保存题目失败:", error);
      message.error("保存失败，请重试");
    }
  };

  const handleCancel = () => {
    setIsModalVisible(false);
    form.resetFields();
    setSelectedQuestion(null);
  };

  const handleEdit = async (record: Question) => {
    try {
      // 类型保护：确保id存在
      const id = record.id;
      if (!id) {
        message.error("题目ID不存在");
        return;
      }

      // 检查是否使用本地模式
      const useLocalMode = !process.env.REACT_APP_API_BASE_URL || 
                          process.env.REACT_APP_API_BASE_URL.includes('localhost:8080');
      
      if (useLocalMode) {
        // 使用本地数据
        setSelectedQuestion(String(id));
        form.setFieldsValue(record);
        setIsModalVisible(true);
        return;
      }

      try {
        // 获取题目详情
        const response = await questionAPI.getQuestion(Number(id));
        if (response.data) {
          setSelectedQuestion(String(id));
          form.setFieldsValue(response.data);
          setIsModalVisible(true);
        }
      } catch (error) {
        console.error("API获取详情失败，使用本地数据:", error);
        // 使用本地数据
        setSelectedQuestion(String(id));
        form.setFieldsValue(record);
        setIsModalVisible(true);
      }
    } catch (error) {
      console.error("获取题目详情失败:", error);
      message.error("获取题目详情失败");
    }
  };

  const handleDelete = (id: string) => {
    confirm({
      title: "确认删除",
      content: "确定要删除这道题目吗？",
      async onOk() {
        try {
          // 检查是否使用本地模式
          const useLocalMode = !process.env.REACT_APP_API_BASE_URL || 
                              process.env.REACT_APP_API_BASE_URL.includes('localhost:8080');
          
                  if (useLocalMode) {
          // 本地删除
          setQuestions(prev => prev.filter(q => q.id !== id));
          message.success("删除成功");
          return;
        }

          await questionAPI.deleteQuestion(Number(id));
          message.success("删除成功");
        } catch (error) {
          console.error("API删除失败，使用本地删除:", error);
          // 本地删除
          setQuestions(prev => prev.filter(q => q.id !== id));
          message.success("删除成功");
        }
        loadQuestions(); // 重新加载题目列表
      },
    });
  };

  // 批量操作处理函数
  const handleCopySelected = async () => {
    try {
      // 检查是否使用本地模式
      const useLocalMode = !process.env.REACT_APP_API_BASE_URL || 
                          process.env.REACT_APP_API_BASE_URL.includes('localhost:8080');
      
      if (useLocalMode) {
        // 本地复制
        const copiedQuestions = selectedQuestions.map(q => ({
          ...q,
          id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
          createTime: new Date().toISOString().split('T')[0],
          updateTime: new Date().toISOString().split('T')[0],
        }));
        setQuestions(prev => [...copiedQuestions, ...prev]);
        message.success(`批量复制 ${selectedRowKeys.length} 道题目成功！`);
        setSelectedRowKeys([]);
        return;
      }

      await questionAPI.copyQuestions(selectedRowKeys as string[]);
      message.success(`批量复制 ${selectedRowKeys.length} 道题目成功！`);
    } catch (error) {
      console.error("API批量复制失败，使用本地复制:", error);
      // 本地复制
      const copiedQuestions = selectedQuestions.map(q => ({
        ...q,
        id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
        createTime: new Date().toISOString().split('T')[0],
        updateTime: new Date().toISOString().split('T')[0],
      }));
      setQuestions(prev => [...copiedQuestions, ...prev]);
      message.success(`批量复制 ${selectedRowKeys.length} 道题目成功！`);
    }
    setSelectedRowKeys([]);
    loadQuestions();
  };

  const handleDeleteSelected = () => {
    confirm({
      title: "确认删除",
      content: `确定要删除选中的 ${selectedRowKeys.length} 道题目吗？`,
      async onOk() {
        try {
          // 检查是否使用本地模式
          const useLocalMode = !process.env.REACT_APP_API_BASE_URL || 
                              process.env.REACT_APP_API_BASE_URL.includes('localhost:8080');
          
          if (useLocalMode) {
            // 本地删除
            setQuestions(prev => prev.filter(q => !selectedRowKeys.includes(q.id)));
            message.success(`批量删除 ${selectedRowKeys.length} 道题目成功！`);
            setSelectedRowKeys([]);
            return;
          }

          await questionAPI.deleteQuestions(selectedRowKeys as string[]);
          message.success(`批量删除 ${selectedRowKeys.length} 道题目成功！`);
        } catch (error) {
          console.error("API批量删除失败，使用本地删除:", error);
          // 本地删除
          setQuestions(prev => prev.filter(q => !selectedRowKeys.includes(q.id)));
          message.success(`批量删除 ${selectedRowKeys.length} 道题目成功！`);
        }
        setSelectedRowKeys([]);
        loadQuestions();
      },
    });
  };

  // 处理试卷模板保存
  const handleTemplateSubmit = async () => {
    try {
      const values = await templateForm.validateFields();

      // 检查是否使用本地模式
      const useLocalMode = !process.env.REACT_APP_API_BASE_URL || 
                          process.env.REACT_APP_API_BASE_URL.includes('localhost:8080');

      if (selectedTemplate) {
        if (useLocalMode) {
          // 本地更新
          setTemplates(prev => prev.map(t => 
            t.id === selectedTemplate ? { ...t, ...values } : t
          ));
          message.success("模板更新成功！");
        } else {
          try {
            await templateAPI.updateTemplate(Number(selectedTemplate), values);
            message.success("模板更新成功！");
          } catch (error) {
            console.error("API模板更新失败，使用本地更新:", error);
            // 本地更新
            setTemplates(prev => prev.map(t => 
              t.id === selectedTemplate ? { ...t, ...values } : t
            ));
            message.success("模板更新成功！");
          }
        }
      } else {
        if (useLocalMode) {
          // 本地创建
          const newTemplate: ExamTemplate = {
            id: Date.now().toString(),
            ...values,
          };
          setTemplates(prev => [newTemplate, ...prev]);
          message.success("模板创建成功！");
        } else {
          try {
            await templateAPI.createTemplate(values);
            message.success("模板创建成功！");
          } catch (error) {
            console.error("API模板创建失败，使用本地创建:", error);
            // 本地创建
            const newTemplate: ExamTemplate = {
              id: Date.now().toString(),
              ...values,
            };
            setTemplates(prev => [newTemplate, ...prev]);
            message.success("模板创建成功！");
          }
        }
      }

      setIsTemplateModalVisible(false);
      templateForm.resetFields();
      setSelectedTemplate(null);
      loadTemplates(); // 重新加载模板列表
    } catch (error) {
      console.error("保存模板失败:", error);
      message.error("保存失败，请重试");
    }
  };

  // 处理试卷生成
  const handleGenerateExam = () => {
    if (templates.length === 0) {
      message.warning("请先创建试卷模板！");
      return;
    }

    // 显示模板选择对话框
    Modal.confirm({
      title: "选择试卷模板",
      width: 600,
      content: (
        <div>
          <p style={{ marginBottom: 16 }}>请选择要使用的试卷模板：</p>
          <List
            dataSource={templates}
            renderItem={(template) => (
              <List.Item
                style={{ 
                  cursor: 'pointer', 
                  border: '1px solid #d9d9d9',
                  borderRadius: '6px',
                  marginBottom: '8px',
                  padding: '12px'
                }}
                onClick={() => {
                  Modal.destroyAll();
                  generateExamWithTemplate(template);
                }}
              >
                <List.Item.Meta
                  title={template.name}
                  description={
                    <Space>
                      <Tag color="blue">总分: {template.totalScore}</Tag>
                      <Tag color="green">时长: {template.duration}分钟</Tag>
                      <span>题目分布: 选择题{template.questionDistribution.choice.count}题, 
                            编程题{template.questionDistribution.programming.count}题, 
                            分析题{template.questionDistribution.analysis.count}题</span>
                    </Space>
                  }
                />
              </List.Item>
            )}
          />
        </div>
      ),
      onCancel() {
        // 用户取消选择
      },
    });
  };

  // 使用指定模板生成试卷
  const generateExamWithTemplate = (template: ExamTemplate) => {
    setIsGenerating(true);
    setGenerationProgress(0);
    setGenerationStatus("正在分析模板要求...");
    
    // 模拟AI试卷生成过程
    let progress = 0;
    const progressInterval = setInterval(() => {
      progress += Math.random() * 15 + 5; // 随机进度增长
      if (progress >= 100) {
        progress = 100;
        clearInterval(progressInterval);
      }
      setGenerationProgress(progress);
      
      // 根据进度更新状态
      if (progress < 20) {
        setGenerationStatus("正在分析模板要求...");
      } else if (progress < 40) {
        setGenerationStatus("正在生成选择题...");
      } else if (progress < 60) {
        setGenerationStatus("正在生成编程题...");
      } else if (progress < 80) {
        setGenerationStatus("正在生成分析题...");
      } else {
        setGenerationStatus("正在优化试卷结构...");
      }
    }, 200);

    // 模拟AI生成题目
    setTimeout(() => {
      try {
        // 根据模板要求AI生成题目
        const generatedQuestions: Question[] = [];
        
        // 为每种题型生成符合要求的题目
        Object.entries(template.questionDistribution).forEach(
          ([type, config]) => {
            const questionType = type as QuestionType;
            const count = config.count;
            const score = config.score / count; // 平均分值
            
            for (let i = 0; i < count; i++) {
              const difficulty = config.difficulty[Math.floor(Math.random() * config.difficulty.length)] as DifficultyLevel;
              
              // 根据题型和难度生成题目内容
              let content = "";
              let answer = "";
              let analysis = "";
              let options: string[] = [];
              
              if (questionType === "choice") {
                const topics = ["JavaScript基础", "React框架", "数据结构", "算法设计", "CSS样式", "HTML语义"];
                const topic = topics[Math.floor(Math.random() * topics.length)];
                content = `关于${topic}，以下哪个选项是正确的？`;
                answer = ["A", "B", "C", "D"][Math.floor(Math.random() * 4)];
                options = [
                  `${topic}的核心概念解释A`,
                  `${topic}的实践应用B`, 
                  `${topic}的进阶特性C`,
                  `${topic}的常见误区D`
                ];
                analysis = `本题考查${topic}的基础知识，正确答案为${answer}。`;
              } else if (questionType === "programming") {
                const tasks = ["数组排序", "字符串处理", "对象操作", "函数编写", "DOM操作", "事件处理"];
                const task = tasks[Math.floor(Math.random() * tasks.length)];
                content = `请编写一个函数来实现${task}功能。`;
                answer = `function ${task.replace(/\s+/g, '')}(data) {\n  // 实现${task}逻辑\n  return result;\n}`;
                analysis = `本题考查编程实践能力，需要理解${task}的实现原理。`;
              } else if (questionType === "analysis") {
                const concepts = ["组件生命周期", "状态管理", "性能优化", "设计模式", "架构设计", "测试策略"];
                const concept = concepts[Math.floor(Math.random() * concepts.length)];
                content = `请分析${concept}在实际项目中的应用场景和最佳实践。`;
                answer = `${concept}是前端开发中的重要概念，主要应用于...`;
                analysis = `本题考查对${concept}的深入理解和实际应用能力。`;
              }
              
              const generatedQuestion: Question = {
                id: `generated_${Date.now()}_${i}`,
                type: questionType,
                difficulty,
                score: Math.round(score),
                content,
                answer,
                analysis,
                knowledge: [questionType === "choice" ? "基础知识" : questionType === "programming" ? "编程实践" : "深度分析"],
                options: questionType === "choice" ? options : undefined,
                tags: [difficulty, questionType],
                createTime: new Date().toISOString().split('T')[0],
                updateTime: new Date().toISOString().split('T')[0],
              };
              
              generatedQuestions.push(generatedQuestion);
            }
          }
        );

        // 计算总分和预估时长
        const totalScore = generatedQuestions.reduce((sum, q) => sum + q.score, 0);
        const estimatedDuration = generatedQuestions.reduce((sum, q) => {
          const baseDuration = q.type === "choice" ? 2 : q.type === "programming" ? 15 : 8;
          return sum + baseDuration;
        }, 0);

        // 设置试卷数据并显示预览
        setExamData({
          templateName: template.name,
          totalScore,
          duration: estimatedDuration,
          questions: generatedQuestions,
        });

        setIsPreviewVisible(true);
        message.success("AI试卷生成成功！");
        
        // 询问是否将生成的题目添加到题库
        Modal.confirm({
          title: "添加到题库",
          content: "是否将AI生成的题目添加到题库中？",
          okText: "添加到题库",
          cancelText: "仅预览",
          onOk: () => {
            handleAddAIGeneratedQuestionsToBank(generatedQuestions);
          },
        });
      } catch (error) {
        console.error("AI试卷生成失败:", error);
        message.error("AI试卷生成失败，请重试");
      } finally {
        setIsGenerating(false);
      }
    }, 3000); // 模拟3秒AI生成时间
  };

  // 复制题目
  const handleCopyQuestion = async (record: Question) => {
    try {
      // 检查是否使用本地模式
      const useLocalMode = !process.env.REACT_APP_API_BASE_URL || 
                          process.env.REACT_APP_API_BASE_URL.includes('localhost:8080');
      
      if (useLocalMode) {
        // 本地复制
        const copiedQuestion: Question = {
          ...record,
          id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
          createTime: new Date().toISOString().split('T')[0],
          updateTime: new Date().toISOString().split('T')[0],
        };
        setQuestions(prev => [copiedQuestion, ...prev]);
        message.success("题目复制成功！");
        return;
      }

      await questionAPI.copyQuestion(Number(record.id));
      message.success("题目复制成功！");
      loadQuestions();
    } catch (error) {
      console.error("API复制失败，使用本地复制:", error);
      // 本地复制
      const copiedQuestion: Question = {
        ...record,
        id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
        createTime: new Date().toISOString().split('T')[0],
        updateTime: new Date().toISOString().split('T')[0],
      };
      setQuestions(prev => [copiedQuestion, ...prev]);
      message.success("题目复制成功！");
    }
  };

  // AI生成题目
  const handleAIGenerate = () => {
    setAiModalVisible(true);
  };

  // AI生成题目加入题库
  const handleAddAIGeneratedQuestionsToBank = (generatedQuestions: Question[]) => {
    try {
      // 将AI生成的题目添加到题库中
      const newQuestions = generatedQuestions.map((question, index) => ({
        ...question,
        id: `ai_generated_${Date.now()}_${index}`,
        createTime: new Date().toISOString().split('T')[0],
        updateTime: new Date().toISOString().split('T')[0],
      }));

      // 更新题目列表
      setQuestions(prev => [...newQuestions, ...prev]);
      
      // 更新分页信息
      setPagination(prev => ({
        ...prev,
        total: prev.total + newQuestions.length,
      }));

      message.success(`成功将${newQuestions.length}道AI生成题目添加到题库！`);
    } catch (error) {
      console.error("添加AI生成题目到题库失败:", error);
      message.error("添加题目失败，请重试");
    }
  };

  // 智能组卷成功回调
  const handleSmartComposerSuccess = (examData: any) => {
    console.log("智能组卷完成:", examData);
    
    // 设置生成的试卷数据
    setExamData({
      templateName: examData.title || `智能组卷${questionType === "exam" ? "试卷" : "作业"}`,
      totalScore: examData.totalScore || 100,
      duration: examData.duration || 120,
      questions: examData.questions || [],
    });
    
    setIsPreviewVisible(true);
    message.success(`智能组卷${questionType === "exam" ? "试卷" : "作业"}完成！`);
    
    // 询问是否将生成的题目添加到题库
    Modal.confirm({
      title: "添加到题库",
      content: "是否将AI生成的题目添加到题库中？",
      okText: "添加到题库",
      cancelText: "仅预览",
      onOk: () => {
        handleAddAIGeneratedQuestionsToBank(examData.questions || []);
      },
    });
  };

  // 保存试卷到考试管理
  const handleSaveToExamManagement = () => {
    if (!examData) {
      message.error("没有可保存的试卷数据");
      return;
    }

    const isExam = questionType === "exam";
    const title = isExam ? "保存试卷" : "保存作业";
    const content = isExam ? 
      "确定要将此试卷保存到考试管理系统吗？保存后可以在考试管理界面中创建考试。" :
      "确定要将此作业保存到作业管理系统吗？保存后可以在作业批改界面中查看。";

    Modal.confirm({
      title,
      content: (
        <div>
          <p>{content}</p>
        </div>
      ),
      onOk: () => {
        // 模拟保存过程
        message.loading(`正在保存${isExam ? "试卷" : "作业"}...`, 2).then(() => {
          // 保存到examStore
          if (isExam) {
            const newPaper = examStore.addPaper({
              name: examData.templateName,
              code: `PAPER_${Date.now()}`,
              courseId: selectedCourse?.id || "c1",
              courseName: selectedCourse?.name || "未知课程",
              totalScore: examData.totalScore,
              duration: examData.duration,
              questionCount: examData.questions.length,
              difficulty: "中等" as const,
              creator: "张教授",
              description: `智能生成的${examData.templateName}`,
              tags: ["智能生成", "AI组卷"],
              questions: examData.questions,
            });
            
            message.success(`试卷"${newPaper.name}"保存成功！`);
            navigate("/teacher/exam-management");
          } else {
            message.success("作业保存成功！");
            navigate("/teacher/homework-grading");
          }
        });
      },
    });
  };

  // 导出试卷
  const handleExportExam = () => {
    if (!examData) {
      message.error("没有可导出的试卷数据");
      return;
    }

    const isExam = questionType === "exam";
    const title = isExam ? "导出试卷" : "导出作业";
    const saveText = isExam ? "保存到考试管理" : "保存到作业管理";

    Modal.confirm({
      title,
      content: "请选择导出方式：",
      cancelText: "取消",
      onCancel: () => Modal.destroyAll(),
      footer: [
        <Button key="cancel" onClick={() => Modal.destroyAll()}>
          取消
        </Button>,
        <Button 
          key="save" 
          type="primary" 
          onClick={() => {
            // 直接执行保存逻辑，不创建新的确认对话框
            const isExam = questionType === "exam";
            message.loading(`正在保存${isExam ? "试卷" : "作业"}...`, 2).then(() => {
              // 保存到examStore
              if (isExam) {
                const newPaper = examStore.addPaper({
                  name: examData.templateName,
                  code: `PAPER_${Date.now()}`,
                  courseId: selectedCourse?.id || "c1",
                  courseName: selectedCourse?.name || "未知课程",
                  totalScore: examData.totalScore,
                  duration: examData.duration,
                  questionCount: examData.questions.length,
                  difficulty: "中等" as const,
                  creator: "张教授",
                  description: `智能生成的${examData.templateName}`,
                  tags: ["智能生成", "AI组卷"],
                  questions: examData.questions,
                });
                
                message.success(`试卷"${newPaper.name}"保存成功！`);
                Modal.destroyAll();
                navigate("/teacher/exam-management");
              } else {
                message.success("作业保存成功！");
                Modal.destroyAll();
                navigate("/teacher/homework-grading");
              }
            });
          }}
        >
          {saveText}
        </Button>,
        <Button key="export" onClick={() => {
          // 模拟导出过程
          message.loading(`正在导出${isExam ? "试卷" : "作业"}...`, 2).then(() => {
            message.success(`${isExam ? "试卷" : "作业"}导出成功！文件已保存到下载文件夹`);
            Modal.destroyAll();
          });
        }}>
          导出文件
        </Button>,
      ],
    });
  };

  // 创建试卷模板
  const handleCreateTemplate = () => {
    setSelectedTemplate(null);
    setIsTemplateModalVisible(true);
  };

  // 编辑试卷模板
  const handleEditTemplate = (template: ExamTemplate) => {
    setSelectedTemplate(template.id);
    templateForm.setFieldsValue(template);
    setIsTemplateModalVisible(true);
  };

  // 删除试卷模板
  const handleDeleteTemplate = (templateId: string) => {
    confirm({
      title: "确认删除",
      content: "确定要删除这个试卷模板吗？",
      async onOk() {
        try {
          // 使用examStore删除模板
          examStore.deleteTemplate(templateId);
          message.success("模板删除成功！");
          loadTemplates(); // 重新加载模板列表
        } catch (error) {
          console.error("删除模板失败:", error);
          message.error("删除失败，请重试");
        }
      },
    });
  };

  // 题目列表列定义
  const columns = [
    {
      title: "类型",
      dataIndex: "type",
      key: "type",
      width: 80,
      render: (type: QuestionType) => {
        const typeMap: Record<QuestionType, { color: string; text: string }> = {
          choice: { color: "blue", text: "选择" },
          programming: { color: "purple", text: "编程" },
          analysis: { color: "cyan", text: "分析" },
          fill: { color: "lime", text: "填空" },
          essay: { color: "geekblue", text: "简答" },
        };
        const typeConfig = typeMap[type] || { color: "default", text: type || "未知" };
        return (
          <TypeTag color={typeConfig.color} $type={type}>
            {typeConfig.text}
          </TypeTag>
        );
      },
    },
    {
      title: "难度",
      dataIndex: "difficulty",
      key: "difficulty",
      width: 80,
      render: (difficulty: DifficultyLevel) => {
        const difficultyMap = {
          easy: { color: "green", text: "简单" },
          medium: { color: "orange", text: "中等" },
          hard: { color: "red", text: "困难" },
        };
        const difficultyConfig = difficultyMap[difficulty] || { color: "default", text: difficulty || "未知" };
        return (
          <DifficultyTag
            color={difficultyConfig.color}
            $difficulty={difficulty}
          >
            {difficultyConfig.text}
          </DifficultyTag>
        );
      },
    },
    {
      title: "分值",
      dataIndex: "score",
      key: "score",
      width: 60,
    },
    {
      title: "题目内容",
      dataIndex: "content",
      key: "content",
      ellipsis: true,
      width: 300,
      render: (content: string) => (
        <Tooltip title={content}>
          <Text ellipsis style={{ maxWidth: 280 }}>
            {content}
          </Text>
        </Tooltip>
      ),
    },
    {
      title: "知识点",
      dataIndex: "knowledge",
      key: "knowledge",
      width: 150,
      render: (knowledge: string[]) => (
        <Space size={[0, 4]} wrap>
          {knowledge.slice(0, 2).map((item) => (
            <Tag key={item} color="blue">
              {item}
            </Tag>
          ))}
          {knowledge.length > 2 && (
            <Tooltip title={knowledge.slice(2).join(", ")}>
              <Tag color="default">+{knowledge.length - 2}</Tag>
            </Tooltip>
          )}
        </Space>
      ),
    },
    {
      title: "更新时间",
      dataIndex: "updateTime",
      key: "updateTime",
      width: 100,
    },
    {
      title: "操作",
      key: "action",
      width: 120,
      fixed: "right" as const,
      render: (_: any, record: Question) => (
        <Space size="small">
          <Tooltip title="编辑">
            <Button
              type="link"
              size="small"
              icon={<EditOutlined />}
              onClick={() => {
                const id = record.id;
                if (id) {
                  setSelectedQuestion(String(id));
                  form.setFieldsValue(record);
                  setIsModalVisible(true);
                }
              }}
            />
          </Tooltip>
          <Tooltip title="复制">
            <Button
              type="link"
              size="small"
              icon={<CopyOutlined />}
              onClick={() => handleCopyQuestion(record)}
            />
          </Tooltip>
          <Tooltip title="删除">
            <Button
              type="link"
              size="small"
              danger
              icon={<DeleteOutlined />}
              onClick={() => {
                const id = record.id;
                if (id) {
                  handleDelete(String(id));
                }
              }}
            />
          </Tooltip>
        </Space>
      ),
    },
  ];

  // 题目表单
  const questionForm = (
    <Form form={form} layout="vertical">
      <Row gutter={16}>
        <Col span={8}>
          <Form.Item
            name="type"
            label="题目类型"
            rules={[{ required: true, message: "请选择题目类型" }]}
          >
            <Select>
              <Option value="choice">选择题</Option>
              <Option value="programming">编程题</Option>
              <Option value="analysis">分析题</Option>
            </Select>
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item
            name="difficulty"
            label="难度"
            rules={[{ required: true, message: "请选择难度" }]}
          >
            <Select>
              <Option value="easy">简单</Option>
              <Option value="medium">中等</Option>
              <Option value="hard">困难</Option>
            </Select>
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item
            name="score"
            label="分值"
            rules={[{ required: true, message: "请输入分值" }]}
          >
            <InputNumber min={1} max={100} style={{ width: "100%" }} />
          </Form.Item>
        </Col>
      </Row>

      <Form.Item
        name="content"
        label="题目内容"
        rules={[{ required: true, message: "请输入题目内容" }]}
      >
        <TextArea rows={4} placeholder="请输入题目内容" />
      </Form.Item>

      <Form.Item
        name="answer"
        label="参考答案"
        rules={[{ required: true, message: "请输入参考答案" }]}
      >
        <TextArea rows={4} placeholder="请输入参考答案" />
      </Form.Item>

      <Form.Item name="analysis" label="解析">
        <TextArea rows={3} placeholder="请输入题目解析" />
      </Form.Item>

      <Form.Item
        name="knowledge"
        label="知识点"
        rules={[{ required: true, message: "请输入知识点" }]}
      >
        <Select mode="tags" placeholder="请输入知识点">
          <Option value="嵌入式基础">嵌入式基础</Option>
          <Option value="操作系统">操作系统</Option>
          <Option value="数据结构">数据结构</Option>
          <Option value="算法">算法</Option>
        </Select>
      </Form.Item>

      <Form.Item name="tags" label="标签">
        <Select mode="tags" placeholder="请输入标签">
          <Option value="重点">重点</Option>
          <Option value="难点">难点</Option>
          <Option value="综合">综合</Option>
        </Select>
      </Form.Item>

      {form.getFieldValue("type") === "choice" && (
        <Form.Item
          name="options"
          label="选项"
          rules={[{ required: true, message: "请输入选项" }]}
        >
          <Select mode="tags" placeholder="请输入选项，每行一个">
            <Option value="A">选项A</Option>
            <Option value="B">选项B</Option>
            <Option value="C">选项C</Option>
            <Option value="D">选项D</Option>
          </Select>
        </Form.Item>
      )}
    </Form>
  );

  return (
    <div style={{ padding: "24px" }}>
      {/* 题目类型选择 */}
                      <Card style={{ marginBottom: 16 }}>
                  <Row gutter={16} align="middle">
                    <Col span={6}>
                      <div style={{ fontWeight: 'bold', fontSize: '16px', marginBottom: 8 }}>
                        {questionType === "exam" ? "考试出题" : "作业出题"}
                      </div>
                      {selectedCourse && (
                        <div style={{ color: '#666', fontSize: '14px' }}>
                          课程：{selectedCourse.name}
                        </div>
                      )}
                    </Col>
                    <Col span={12}>
                      <Radio.Group
                        value={questionType}
                        onChange={(e) => setQuestionType(e.target.value)}
                        buttonStyle="solid"
                      >
                        <Radio.Button value="exam">考试题</Radio.Button>
                        <Radio.Button value="homework">作业题</Radio.Button>
                      </Radio.Group>
                    </Col>
                    <Col span={6} style={{ textAlign: 'right' }}>
                      <Space>
                        <Button
                          icon={<FileTextOutlined />}
                          onClick={() => navigate("/teacher/exam-generation/templates")}
                        >
                          模板管理
                        </Button>
                        {questionType === "homework" && (
                          <Button
                            type="primary"
                            onClick={() => navigate("/teacher/homework-grading")}
                          >
                            查看作业批改
                          </Button>
                        )}
                        {questionType === "exam" && (
                          <Button
                            type="primary"
                            onClick={() => navigate("/teacher/exam-management")}
                          >
                            查看考试管理
                          </Button>
                        )}
                      </Space>
                    </Col>
                  </Row>
                </Card>

      <Card>
        <div style={{ marginBottom: 16 }}>
          <Row gutter={16}>
            <Col span={18}>
              <Form form={searchForm} layout="inline" onFinish={handleSearch}>
                <Form.Item name="keyword">
                  <Input
                    placeholder="搜索题目内容"
                    allowClear
                    style={{ width: 200 }}
                  />
                </Form.Item>
                <Form.Item name="type">
                  <Select
                    placeholder="题目类型"
                    allowClear
                    style={{ width: 120 }}
                  >
                    <Option value="choice">选择题</Option>
                    <Option value="programming">编程题</Option>
                    <Option value="analysis">分析题</Option>
                  </Select>
                </Form.Item>
                <Form.Item name="difficulty">
                  <Select placeholder="难度" allowClear style={{ width: 100 }}>
                    <Option value="easy">简单</Option>
                    <Option value="medium">中等</Option>
                    <Option value="hard">困难</Option>
                  </Select>
                </Form.Item>
                <Form.Item>
                  <Button type="primary" htmlType="submit" loading={loading}>
                    搜索
                  </Button>
                </Form.Item>
              </Form>
            </Col>
            <Col span={6}>
              <Space>
                {/* <Button
                  type="primary"
                  icon={<RobotOutlined />}
                  onClick={() => setSmartComposerVisible(true)}
                >
                  AI智能组卷
                </Button> */}
                <Button
                  icon={<BulbOutlined />}
                  onClick={() => setAiModalVisible(true)}
                >
                  AI生成题目
                </Button>
                <Button icon={<PlusOutlined />} onClick={showModal}>
                  手动添加
                </Button>
              </Space>
            </Col>
          </Row>
        </div>

        <Alert
          message="智能出题助手"
          description="您可以使用AI智能组卷功能快速生成完整试卷，或使用AI生成题目功能批量创建题目。支持拖拽排序和自定义分值。"
          type="info"
          style={{ marginBottom: 16 }}
        />

        {/* 模板管理区域 */}
        <Card title="试卷模板管理" style={{ marginBottom: 16 }}>
          <div style={{ marginBottom: 16 }}>
            <Space>
              <Button 
                type="primary" 
                icon={<PlusOutlined />} 
                onClick={handleCreateTemplate}
              >
                创建模板
              </Button>
              <Button 
                icon={<FileTextOutlined />} 
                onClick={handleGenerateExam}
                disabled={templates.length === 0}
              >
                使用模板生成试卷
              </Button>
            </Space>
          </div>
          
          {templates.length > 0 ? (
            <List
              dataSource={templates}
              renderItem={(template) => (
                <List.Item
                  actions={[
                    <Button 
                      key="edit" 
                      type="link" 
                      icon={<EditOutlined />}
                      onClick={() => handleEditTemplate(template)}
                    >
                      编辑
                    </Button>,
                    <Button 
                      key="use" 
                      type="link" 
                      icon={<FileTextOutlined />}
                      onClick={() => generateExamWithTemplate(template)}
                    >
                      使用
                    </Button>,
                    <Button 
                      key="delete" 
                      type="link" 
                      danger 
                      icon={<DeleteOutlined />}
                      onClick={() => handleDeleteTemplate(template.id)}
                    >
                      删除
                    </Button>,
                  ]}
                >
                  <List.Item.Meta
                    title={
                      <div>
                        <div style={{ fontWeight: 'bold', fontSize: '16px' }}>{template.name}</div>
                        {template.description && (
                          <div style={{ fontSize: '12px', color: '#666', marginTop: '4px' }}>
                            {template.description}
                          </div>
                        )}
                      </div>
                    }
                    description={
                      <div>
                        <Space wrap style={{ marginBottom: '8px' }}>
                          <Tag color="blue">总分: {template.totalScore}</Tag>
                          <Tag color="green">时长: {template.duration}分钟</Tag>
                          <Tag color="orange">选择题: {template.questionDistribution.choice.count}题</Tag>
                          <Tag color="purple">编程题: {template.questionDistribution.programming.count}题</Tag>
                          <Tag color="cyan">分析题: {template.questionDistribution.analysis.count}题</Tag>
                          {template.questionDistribution.fill && (
                            <Tag color="lime">填空题: {template.questionDistribution.fill.count}题</Tag>
                          )}
                          {template.questionDistribution.essay && (
                            <Tag color="geekblue">简答题: {template.questionDistribution.essay.count}题</Tag>
                          )}
                        </Space>
                        <div style={{ fontSize: '12px', color: '#999' }}>
                          {template.subject && <span>学科: {template.subject} | </span>}
                          {template.difficulty && <span>难度: {template.difficulty} | </span>}
                          {template.usageCount && <span>使用次数: {template.usageCount} | </span>}
                          {template.isDefault && <Tag color="gold">默认模板</Tag>}
                        </div>
                      </div>
                    }
                  />
                </List.Item>
              )}
            />
          ) : (
            <Empty 
              description="暂无试卷模板" 
              image={Empty.PRESENTED_IMAGE_SIMPLE}
            >
              <Button type="primary" onClick={handleCreateTemplate}>
                创建第一个模板
              </Button>
            </Empty>
          )}
        </Card>

        {selectedRowKeys.length > 0 && (
          <div style={{ marginBottom: 16 }}>
            <Alert
              message={`已选择 ${selectedRowKeys.length} 道题目`}
              type="success"
              action={
                <Space>
                  <Button size="small" onClick={handleCopySelected}>
                    批量复制
                  </Button>
                  <Button size="small" onClick={handleDeleteSelected} danger>
                    批量删除
                  </Button>
                  <Button size="small" onClick={() => setSelectedRowKeys([])}>
                    取消选择
                  </Button>
                </Space>
              }
            />
          </div>
        )}

        <Table
          rowSelection={{
            selectedRowKeys,
            onChange: (keys, rows) => {
              setSelectedRowKeys(keys);
              setSelectedQuestions(rows);
            },
          }}
          columns={columns}
          dataSource={questions}
          rowKey="id"
          loading={questionsLoading}
          pagination={{
            total: questions.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
        />

        {/* 题目编辑模态框 */}
        <Modal
          title={selectedQuestion ? "编辑题目" : "添加题目"}
          open={isModalVisible}
          onOk={handleOk}
          onCancel={handleCancel}
          width={800}
        >
          {questionForm}
        </Modal>

        {/* 试卷模板模态框 */}
        <Modal
          title={selectedTemplate ? "编辑试卷模板" : "创建试卷模板"}
          open={isTemplateModalVisible}
          onOk={handleTemplateSubmit}
          onCancel={() => {
            setIsTemplateModalVisible(false);
            templateForm.resetFields();
            setSelectedTemplate(null);
          }}
          width={800}
        >
          <TemplateForm form={templateForm} />
        </Modal>

        {/* 试卷预览模态框 */}
        <Modal
          title="试卷预览"
          open={isPreviewVisible}
          onCancel={() => setIsPreviewVisible(false)}
          width={1000}
          footer={[
            <Button key="back" onClick={() => setIsPreviewVisible(false)}>
              关闭
            </Button>,
            <Button
              key="download"
              type="primary"
              icon={<FileTextOutlined />}
              onClick={handleExportExam}
            >
              导出试卷
            </Button>,
          ]}
        >
          {examData && (
            <ExamPreview
              examData={{
                templateName: examData.templateName,
                totalScore: examData.totalScore,
                duration: examData.duration,
                questions: examData.questions.map((q) => ({
                  id: q.id || "",
                  type: q.type as QuestionType,
                  difficulty: q.difficulty as DifficultyLevel,
                  score: q.score,
                  content: q.content,
                  answer: q.answer,
                  knowledge: Array.isArray(q.knowledge) ? q.knowledge : [],
                  options: q.options,
                  analysis: q.analysis,
                  tags: q.tags,
                  createTime: q.createTime || new Date().toISOString(),
                  updateTime: q.updateTime || new Date().toISOString(),
                })),
              }}
            />
          )}
        </Modal>

        {/* AI生成题目模态框 */}
        <AIGenerationModal
          visible={aiModalVisible}
          onCancel={() => setAiModalVisible(false)}
          onSuccess={(newQuestions: ServiceQuestion[]) => {
            // 转换ServiceQuestion到本地Question类型
            const convertedQuestions: Question[] = newQuestions.map((q) => ({
              id: String(q.id || ""),
              type: q.type as QuestionType,
              difficulty: q.difficulty as DifficultyLevel,
              score: q.score,
              content: q.content,
              answer: String(q.answer),
              knowledge: Array.isArray(q.knowledgePoint)
                ? [q.knowledgePoint]
                : [q.knowledgePoint || ""],
              options: q.options,
              analysis: q.analysis,
              tags: [],
              createTime: new Date().toISOString(),
              updateTime: new Date().toISOString(),
            }));
            
            // 使用专门的函数来添加AI生成题目到题库
            handleAddAIGeneratedQuestionsToBank(convertedQuestions);
            setAiModalVisible(false);
          }}
        />

        {/* AI生成进度模态框 */}
        <Modal
          title="AI试卷生成中"
          open={isGenerating}
          footer={null}
          closable={false}
          maskClosable={false}
          width={500}
        >
          <div style={{ textAlign: 'center', padding: '20px' }}>
            <Spin size="large" />
            <div style={{ marginTop: 16 }}>
              <Progress 
                percent={generationProgress} 
                status={generationProgress >= 100 ? "success" : "active"}
                strokeColor={{
                  '0%': '#108ee9',
                  '100%': '#87d068',
                }}
              />
            </div>
            <div style={{ marginTop: 16, fontSize: '14px', color: '#666' }}>
              {generationStatus}
            </div>
            <div style={{ marginTop: 8, fontSize: '12px', color: '#999' }}>
              请稍候，AI正在为您生成试卷...
            </div>
          </div>
        </Modal>

        {/* AI智能组卷模态框 */}
        <SmartComposer
          visible={smartComposerVisible}
          onCancel={() => setSmartComposerVisible(false)}
          onSuccess={handleSmartComposerSuccess}
        />
      </Card>
    </div>
  );
};

export default ExamGeneration;
